/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imat;

import java.awt.Dimension;
import java.text.DecimalFormat;
import javax.swing.DefaultListModel;
import se.chalmers.ait.dat215.project.Order;
import se.chalmers.ait.dat215.project.ShoppingCart;
import se.chalmers.ait.dat215.project.ShoppingItem;

/**
 *
 * @author Andreas
 */
public class TrolleyItemPresenter {

    private TrolleyItemView trolleyItemView;
    private ShoppingCart shoppingCart;
    private String name;
    private int maxHeight;

    public TrolleyItemPresenter(TrolleyItemView trolleyItemView) {
        this.trolleyItemView = trolleyItemView;
    }

    public void receiptButtonClicked() {
        if (trolleyItemView.getReceiptPanel().isVisible()) {
            this.trolleyItemView.getReceiptPanel().setVisible(false);
            this.trolleyItemView.getShowReceipt().setText("Visa varor");
            this.trolleyItemView.setPreferredSize(new Dimension(536, 40));
            this.trolleyItemView.revalidate();
        }
        else {
            this.trolleyItemView.getReceiptPanel().setVisible(true);
            this.trolleyItemView.getShowReceipt().setText("Göm varor");
            this.trolleyItemView.setPreferredSize(new Dimension(536, maxHeight));
            this.trolleyItemView.revalidate();
        }
    }

    public String fillOut(String in, int n) {
        StringBuilder out = new StringBuilder(in);
        for (int i=0; i<n-in.length(); i++) {
            out.append(' ');
        }
        return out.toString();
    }

    public void setShoppingCart(ShoppingCart shoppingCart, String name) {
        this.shoppingCart = shoppingCart;
        this.name = name;

        DefaultListModel listModel = new DefaultListModel();

        DecimalFormat nf = new DecimalFormat();
        nf.setMinimumFractionDigits(2);

        for (ShoppingItem item : shoppingCart.getItems()) {
            listModel.addElement(
                    fillOut(item.getProduct().getName(), 16)+" "+
                    fillOut(item.getAmount()+" "+item.getProduct().getUnitSuffix()+" * "+
                    nf.format(item.getProduct().getPrice()), 32)+" : "+
                    nf.format(item.getTotal())+" kr"
            );
        }
        listModel.addElement(fillOut("", 48)+"  : "+nf.format(shoppingCart.getTotal())+" kr");

        trolleyItemView.getReceiptList().setModel(listModel);

        trolleyItemView.getNameLabel().setText(name);
        trolleyItemView.getCountLabel().setText(Integer.toString(shoppingCart.getItems().size())+" st");
        trolleyItemView.getPriceLabel().setText(Double.toString(shoppingCart.getTotal())+" kr");

        maxHeight = 60 + 20*shoppingCart.getItems().size()+1;

    }

    public void buyTrolley() {
        DataHandler.getInstance().addSavedCartToTrolley(shoppingCart);
    }

    public void removeTrolley() {
        DataHandler.getInstance().removeCart(name);
    }

}
